<?php
/**
 * Term extractor
 *
 * PHP version 5
 *
 * @category   Web
 * @package    Data2People
 * @subpackage Controllers
 * @author     Mike Bevz <mike.bevz@data2people>
 * @copyright  2007-2008 (c) Mike Bevz
 * @license    The BSD License http://data2people.com/license.txt
 * @version    SVN: $Id: TermExtractor.php 18 2008-12-03 06:46:09Z michael.bevz $
 *
 *
 */

class TV_Text_TermExtractor
{
    private $_yahooID = 'wCC2hnfV34F_aWZgXV6kEuFQZBN4iJ0NCuNap59PKntdDRqb5iSQfDZ8JiwcUth6';
     
    /**
     * Returns tags for given $text and $query
     *
     * @param string $text  Text to be tagged
     * @param string $query Text to fine-tune tagging
     *
     * @return array
     * @throws TV_Text_Exception If $text is not string
     */
    public function getTags($text, $query = null)
    {
        if (!is_string($text)) {
            throw new TV_Text_Exception(__METHOD__.' requires string as argument, got '.gettype($text));
        }
         
        $analyzer = new TV_Text_Analyzer();
         
        $cText = $analyzer->cleanTextPunc($text);
        if ($cText == '') {
            return false;
        }
         
        if ($query) {
            $cQuery = $analyzer->cleanTextPunc($query);
        }
         
        $te = new Zend_Rest_Client('http://search.yahooapis.com/ContentAnalysisService/V1/termExtraction');
        $te->appid($this->_yahooID);
        $te->context($cText);
        if ($query) {
            $te->query($cQuery);
        }
        $result = $te->get();
        if ($result->Message) {
            $errors = '';
            foreach($result->Message as $message) {
                $errors .= $message."\n";
            }
            throw new TV_Text_Exception(__METHOD__.': '.$errors.'. Text given: '.$cText);
        }
         
        if ($result->Result) {
            $array = array();
            foreach($result->Result as $result) {
                $array[]  = (string)$result;
            }
             
            return $array;
        }
    }
}